#include <stdio.h>
#include <sys/types.h>
#include "lfs.h"
#include "los_fs.h"
#include "littlefs.h"

struct fs_cfg {
    CHAR *mount_point;
    struct PartitionCfg partCfg;
};

int LittlefsInit()
{
    INT32 ret;
    struct fs_cfg fs[LOSCFG_LFS_MAX_MOUNT_SIZE] = {0};

    INT32 lengthArray[1] = {0x800000};
    INT32 addrArray[1] = {0};
    ret = LOS_DiskPartition("spiflashs", "littlefs", lengthArray, addrArray, 1);
    //printf("%s: DiskPartition %s\n", __func__, (ret == 0) ? "succeed" : "failed");
    if (ret != 0) {
        return -1;
    }

    fs[0].mount_point = "/data";
    fs[0].partCfg.partNo = 0;
    fs[0].partCfg.blockSize = 4096; /* 4096, lfs block size */
    fs[0].partCfg.blockCount = 2048; /* 2048, lfs block count */
    fs[0].partCfg.readFunc = LittlefsRead;
    fs[0].partCfg.writeFunc = LittlefsProg;
    fs[0].partCfg.eraseFunc = LittlefsErase;

    fs[0].partCfg.readSize = 256; /* 256, lfs read size */
    fs[0].partCfg.writeSize = 256; /* 256, lfs prog size */
    fs[0].partCfg.cacheSize = 256; /* 256, lfs cache size */
    fs[0].partCfg.lookaheadSize = 64; /* 16, lfs lookahead size */
    fs[0].partCfg.blockCycles = 1000; /* 1000, lfs block cycles */

    ret = LOS_PartitionFormat("spiflashs", "littlefs", &fs[0].partCfg);
    //printf("%s: PartitionFormat %s\n", __func__, (ret == 0) ? "succeed" : "failed");
    if (ret != 0) {
        return -1;
    }

    ret = mount(NULL, fs[0].mount_point, "littlefs", 0, &fs[0].partCfg);
    //printf("%s: mount fs on '%s' %s\n", __func__, fs[0].mount_point, (ret == 0) ? "succeed" : "failed");
    if (ret != 0) {
        return -1;
    }

    ret = mkdir(fs[0].mount_point, 0777); /* 0777, set dir permissions */
    //printf("%s: mkdir '%s' %s\n", __func__, fs[0].mount_point, (ret == 0) ? "succeed" : "failed");
    if (ret != 0) {
        return -1;
    }

    return 0;
}